﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using System.Threading;
using Cowboy.Sockets;
using Newtonsoft.Json;

namespace MeterMocker
{
    public partial class Form1 : Form
    {
        private TcpSocketClient _client;
        private SerialPort _serialPort;

        public Form1()
        {

             
            _serialPort = new SerialPort();
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] portList = SerialPort.GetPortNames();
            var comNames = portList.ToList();
            this.comComNames.DataSource = comNames;

            string clientIp = ConfigurationManager.AppSettings["clientIp"];
            string portNum = ConfigurationManager.AppSettings["portNum"];
            txtIP.Text = clientIp;
            txtPort.Text = portNum;
            tslblSport.Text = @"串口已关闭";
            tslblTcp.Text = @"tcp已断开连接";
        }

        ////握手 type = meter
        //StringBuilder str = new StringBuilder();
        //        //唯一标识符暂用
        //        string serial = System.Guid.NewGuid().ToString();
        //        str.Append("{\"version\":\"1.0.0.0\",\"serial\":\""+serial+ "\",\"type\":\"meter\"}");


        private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Thread.Sleep(500);
            int n = _serialPort.BytesToRead;
            byte[] data = new byte[n];
            _serialPort.Read(data, 0, data.Length);
            string temp = Encoding.Default.GetString(data);
            //if (temp.Contains("AD_2")) return;
            this.Invoke(new Action(() =>
            {
                txtInfo.Text += "recv SerialPort:" + temp + "\r\n";
            }));
            if (_client.Connected)
            {
                if (temp.Count(i => i == '{') > 1)
                {
                    var position = temp.IndexOf('}');
                    var first = temp.Substring(0, position + 1);

                    _client.Send(Encoding.UTF8.GetBytes(first));
                    var last = temp.Substring( position + 1,temp.Length- position - 1);
                    _client.Send(Encoding.UTF8.GetBytes(last));
                    return;
                }
                _client.Send(Encoding.UTF8.GetBytes(temp));
            }
        }

        private void btnSPlink_Click(object sender, EventArgs e)
        {
            try
            {
                _serialPort.PortName = comComNames.SelectedItem.ToString();
                _serialPort.BaudRate = 9600;
                _serialPort.DataBits = 8;
                _serialPort.StopBits = StopBits.One;
                _serialPort.Parity = Parity.None;
                if (!_serialPort.IsOpen)
                {
                    _serialPort.Open();
                    _serialPort.DataReceived -= _serialPort_DataReceived;
                    _serialPort.DataReceived += _serialPort_DataReceived;
                    tslblSport.Text = @"串口已连接";
                    btnSPlink.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                tslblSport.Text = @"串口已关闭";
                btnSPlink.Enabled = true;
                MessageBox.Show(ex.Message);
            }
        }

        private void btnTcp_Click(object sender, EventArgs e)
        {
            try
            {
                int port;
                int.TryParse(txtPort.Text, out port);
                IPAddress ipAddress = IPAddress.Parse(txtIP.Text);
                IPEndPoint ep = new IPEndPoint(ipAddress, port);
                var config = new TcpSocketClientConfiguration();
                config.FrameBuilder = new LengthFieldBasedFrameBuilder(LengthField.FourBytes);
                _client = new TcpSocketClient(ep, config);
               _client.Connect();
                _client.ServerConnected += _client_ServerConnected;
                _client.ServerDataReceived += _client_ServerDataReceived;
                _client.ServerDisconnected += _client_ServerDisconnected;
            }
            catch (Exception ex)
            {
                btnTcp.Enabled = true;
                tslblTcp.Text = @"tcp已断开连接";
                MessageBox.Show(ex.Message);
            }
        }

        //tcp收数据
        private void _client_ServerDataReceived(object sender, TcpServerDataReceivedEventArgs e)
        {
            var data = Encoding.UTF8.GetString(e.Data);
            this.Invoke(new Action(() =>
            {
                txtInfo.Text += "recv DS:" + data + "\r\n";
            }));

            if (!_serialPort.IsOpen)
                return;
            if (data == "#getSerial")
            {
                _serialPort.Write($"\"{data}\"");
            }
            else
            {
                _serialPort.Write(data);
            }
        }

        private void _client_ServerDisconnected(object sender, TcpServerDisconnectedEventArgs e)
        {
            btnTcp.Enabled = true;
            tslblTcp.Text = @"tcp已断开连接";
        }

        

        private void _client_ServerConnected(object sender, TcpServerConnectedEventArgs e)
        {
            btnTcp.Enabled = false;
            tslblTcp.Text = @"tcp已连接";
        }

        //模拟AP 发题
        private void button1_Click(object sender, EventArgs e)
        {
            if (_client.Connected)
            {
                var j = JObject.FromObject(new
                {
                    serial = "F52700E4031200",
                    km = "km1",
                    titleid = 1,
                    seattype = 0
                });
                _client.Send(Encoding.UTF8.GetBytes(j.ToString()));
            }
        }
        
        private void button2_Click(object sender, EventArgs e)
        {
            TcpClient tcpclient = new TcpClient();
            tcpclient.Connect("222.187.129.131",20300);
            string msg = "{test: 100}";
            var bsMsg = Encoding.Default.GetBytes(msg);
            var bsLen = BitConverter.GetBytes(bsMsg.Length);
            bsLen[0] = 0;
            bsLen[3] = 11;
            tcpclient.GetStream().Write(bsLen, 0, 4);
            tcpclient.GetStream().Write(bsMsg, 0, bsMsg.Length);
        }

      

        private void button3_Click(object sender, EventArgs e)
        {
            if (_client.Connected)
            {
                var j = JObject.FromObject(new
                {
                    serial = "meter1",
                    version = "0.0.1版本",
                    type="meter"
                });
                _client.Send(Encoding.UTF8.GetBytes(j.ToString()));
            }
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            if (_client.Connected)
            {
                var j = JObject.FromObject(new
                {
                   step=txtContent.Text.Trim()
                });
                _client.Send(Encoding.UTF8.GetBytes(j.ToString()));
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (_client.Connected)
            {
                var j = JObject.FromObject(new
                {
                    submit = "submit"
                });
                _client.Send(Encoding.UTF8.GetBytes(j.ToString()));
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            TcpClient tcpclient = new TcpClient();
            tcpclient.Connect("222.187.129.131", 20300);
            string msg = "{test: 100}";
            var bsMsg = Encoding.Default.GetBytes(msg);
            var bsLen = BitConverter.GetBytes(bsMsg.Length);
            bsLen[0] = 0;
            bsLen[3] =(byte) bsMsg.Length;
            tcpclient.GetStream().Write(bsLen, 0, 4);
            tcpclient.GetStream().Write(bsMsg, 0, bsMsg.Length);
        }

        private void button6_Click(object sender, EventArgs e)
        {
            string content = "{ \"submit\":{ \"nr\":\"0\",\"items\":[{ \"name\":\"hj_argon_送电次序\",\"value\":0},{ \"name\":\"hj_argon_闭电次序\",\"value\":0},{ \"name\":\"hj_argon_打开排风\",\"value\":5},{ \"name\":\"hj_argon_关闭排风 \",\"value\":0},{ \"name\":\"hj_argon_电弧电压  \",\"value\":0},{ \"name\":\"hj_argon_焊接电流\",\"value\":0},{ \"name\":\"hj_argon_氩气瓶气阀速度\",\"value\":5},{\"name\":\"hj_argon_引弧\",\"value\":0},{ \"name\":\"hj_argon_引弧次数\",\"value\":0},{ \"name\":\"hj_argon_焊接速度\",\"value\":0},{ \"name\":\"hj_argon_焊缝宽度 \",\"value\":4},{ \"name\":\"hj_argon_焊缝长度\",\"value\":0},{ \"name\":\"hj_argon_焊缝不脱节\",\"value\":0},{\"name\":\"hj_argon_总分\",\"value\":0}]}}";

            var jdata = JObject.Parse(content);
            var result = JsonConvert.DeserializeObject<ContentJson>(content);
            var score = result.submit.items.Sum(i => i.value);
        }

        class ContentJson
        {
            public SubmitJson submit { get; set; }
        }

        class SubmitJson
        {
            public string nr { get; set; }
            public List<NameValue> items { get; set; }
        }

        class NameValue
        {
            public string name { get; set; }
            public decimal value { get; set; }
        }

        private void button5_Click_1(object sender, EventArgs e)
        {
            var content = txtWeldcontent.Text.Trim();
            _client.Send(Encoding.UTF8.GetBytes(content));
        }
    }

}
